package com.cyy.common.config.satoken;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyy.common.mapper.MenuMapper;
import com.cyy.common.mapper.RoleMapper;
import com.cyy.common.mapper.UserRoleMapper;
import com.cyy.common.pojo.entity.UserRole;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class MyStpInterface implements StpInterface {

    private final MenuMapper menuMapper;

    private final RoleMapper roleMapper;

    private final UserRoleMapper userRoleMapper;

    /**
     * 获取权限列表
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 权限列表
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {

        List<UserRole> userRoles = userRoleMapper.selectList(Wrappers.<UserRole>lambdaQuery()
                .select(UserRole::getRoleId)
                .eq(UserRole::getUserId, loginId));

        if (CollectionUtil.isNotEmpty(userRoles)) {
            List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            return menuMapper.getPermsByRoleIds(roleIds);
        }
        return null;
    }

    /**
     * 获取角色列表
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 角色列表
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return roleMapper.getRoleCodesByUserId(loginId);
    }
}
